<template>
  <div class="studentManage" style="padding: 15px">

    <div class="student-form">
      <el-form :model="selectStudent" ref="selectStudent" class="demo-dialogForm" v-show="toggle"
               inline>
        <el-form-item label="姓名" prop="name" size="medium">
          <el-input v-model="selectStudent.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username" size="medium">
          <el-input v-model="selectStudent.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender" size="medium">
          <el-input v-model="selectStudent.gender" placeholder="请输入性别"></el-input>
        </el-form-item>
        <el-form-item label="生日" prop="time" size="medium">
          <el-date-picker
            v-model="time.birthdayTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="入学日期" prop="time" size="medium">
          <el-date-picker
            v-model="time.enrollmentTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="毕业日期" prop="time" size="medium">
          <el-date-picker
            v-model="time.graduationTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="selectButton" size="mini">搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="reset" size="mini">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="student-button">
      <el-row>
        <el-button icon="el-icon-plus" plain type="primary" @click="insertHandler" size="mini">新增</el-button>
        <el-button icon="el-icon-delete" plain type="danger" @click="deleteHandler" size="mini">删除</el-button>
        <div class="right-toolbar">
          <el-tooltip class="item" effect="dark" :content="toggle?'隐藏搜索':'显示搜索'" placement="top">
            <el-button size="mini" circle icon="el-icon-search" @click="toggle=!toggle"/>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <el-button size="mini" circle icon="el-icon-refresh" @click="pageListStudent"/>
          </el-tooltip>
        </div>
      </el-row>
    </div>

    <div class="student-table">
      <el-table :data="students" tooltip-effect="dark" style="width: 100%;margin-top: 15px" :header-cell-style="style"
                @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="50"></el-table-column>
        <el-table-column align="center" prop="id" label="序号" width="60"></el-table-column>
        <el-table-column align="center" prop="name" label="姓名"></el-table-column>
        <el-table-column align="center" prop="username" label="用户名"></el-table-column>
        <el-table-column align="center" prop="age" label="年龄"></el-table-column>
        <el-table-column align="center" prop="gender" label="性别">
          <template slot-scope="scope">
            {{ scope.row.gender === 0 ? '男' : scope.row.gender === 1 ? '女' : '未知' }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="clazz.name" label="所在班级" width="110"></el-table-column>
        <el-table-column align="center" prop="enrollmentDate" label="入学日期" width="160"></el-table-column>
        <el-table-column align="center" prop="graduationDate" label="毕业日期" width="160"></el-table-column>
        <el-table-column align="center" prop="address" label="地址"></el-table-column>
        <el-table-column align="center" prop="avator" label="头像" width="100">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.avatar"
              class="img"
              :src="baseApi+scope.row.avatar"
              :preview-src-list="[baseApi+scope.row.avatar]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="resume" label="简历" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-link :href="baseApi+'/'+scope.row.resume" v-if="scope.row.resume">
              {{ scope.row.resume }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="140">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" size="mini" @click="updateRow(scope.row)">修改
            </el-button>
            <el-button type="text" icon="el-icon-delete" size="mini" @click="deleteRow(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="student-pager">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 20, 50, 100]"
        :page-size="pageSize"
        layout="->,total, sizes, prev, pager, next, jumper"
        :total="totalPage">
      </el-pagination>
    </div>

    <el-dialog
      :title="dialogTitle" :visible.sync="dialogVisible" width="770px">
      <el-form :model="dialogForm" ref="dialogForm" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-col :span="10">
            <el-input v-model="dialogForm.name"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-col :span="10">
            <el-input v-model="dialogForm.username"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-col :span="10">
            <el-input v-model="dialogForm.age"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="dialogForm.gender">
            <el-radio :label='0'>男</el-radio>
            <el-radio :label='1'>女</el-radio>
            <el-radio :label='2'>未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所在班级" prop="classId">
          <el-col :span="22">
            <el-select v-model="dialogForm.classId" placeholder="请选择班级">
              <div v-for="item in classes">
                <el-option :label="item.name" :value="item.id"></el-option>
              </div>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="入学日期" prop="enrollmentDate">
          <el-date-picker
            v-model="dialogForm.enrollmentDate"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="请选择入学日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="毕业日期" prop="graduationDate">
          <el-date-picker
            v-model="dialogForm.graduationDate"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="请选择毕业日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input type="textarea" v-model="dialogForm.address"></el-input>
        </el-form-item>
        <div style="position: absolute; top: 100px ; left:330px;">
          <el-form-item prop="avatar">
            <el-upload
              class="avatar-uploader"
              :action="uploadApi"
              :show-file-list="false"
              :on-success="(res,file,fileList)=>handleUploadSuccess(res,file,fileList,'AVATAR')"
              :before-upload="(file)=>handleBeforeUpload(file,'AVATAR')"
              :on-remove="(file,fileList)=>handleRemove(file,fileList,'AVATAR')">
              <img v-if="dialogForm.avatar" :src="baseApi+dialogForm.avatar" class="img"/>
              <i v-else class="el-icon-plus img-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="简历" prop="resume">
            <el-upload
              class="upload-demo"
              :action="uploadApi"
              :limit="1"
              :file-list="resumeList"
              :on-success="(res,file,fileList)=>handleUploadSuccess(res,file,fileList,'RESUME')"
              :before-upload="(file)=>handleBeforeUpload(file,'RESUME')"
              :on-remove="(file,fileList)=>handleRemove(file,fileList,'RESUME')">
              <el-button size="small" type="primary">这里点击上传简历</el-button>
              <div slot="tip" class="el-upload-tip">请上传大小不超过 <b>5MB</b> 的 <b>doc/xls/ppt/txt/pdf</b> 文件</div>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogSubmitHandler()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {pageList, editList, deleteList, classList} from "@/api/campus/student";

const BASE_API = process.env.VUE_APP_BASE_API
const UPLOAD_API = BASE_API + 'campus/file/upload'

export default {
  name: "index.vue",
  watch: {
    // 监听resume构造resumeList
    'dialogForm.resume': {
      handler(val) {
        if (!val) {
          this.resumeList = []
          return
        }
        const arr = val.toString().split("/")
        const arr1 = arr[arr.length - 2].split('_')
        const name = arr1[0]
        this.resumeList = [{
          name: name,
          url: val
        }]
      }
    }
  },
  data() {
    return {
      baseApi: BASE_API,
      uploadApi: UPLOAD_API,
      // 搜索框
      toggle: true,
      selectStudent: {
        name: '',
        username: '',
        gender: '',
        birthdayStartTime: '',
        birthdayEndTime: '',
        enrollmentStartTime: '',
        enrollmentEndTime: '',
        graduationStartTime: '',
        graduationEndTime: '',
      },
      time: {
        birthdayTime: '',
        enrollmentTime: '',
        graduationTime: ''
      },
      // 表格
      students: [],
      classes: [],
      ids: [],
      // 分页
      totalPage: 0,
      pageSize: 5,
      pageNum: 1,
      // 弹框
      dialogTitle: '',
      dialogVisible: false,
      dialogForm: {
        name: '',
        username: '',
        age: '',
        gender: '',
        classId: '',
        enrollmentDate: '',
        graduationDate: '',
        address: '',
        avatar: '',
        resume: ''
      },
      resumeList: []
    }
  },
  created() {
    this.pageListStudent()
    this.listClass()
  },
  methods: {
    style() {
      return "background-color:#eee;color:#000"
    },
    // 复选 ids
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.ids = this.multipleSelection.map(i => i.id)
    },
    // 分页渲染list
    pageListStudent() {
      pageList(this.pageNum, this.pageSize, this.selectStudent).then((res) => {
        console.log(res)
        this.totalPage = res.data.count
        this.students = res.data.list
      })
    },
    // 班级list
    listClass() {
      classList().then(res => {
        console.log(res.data)
        this.classes = res.data.list
      })
    },
    // 查询按钮
    selectButton() {
      this.selectStudent.birthdayStartTime = this.time.birthdayTime[0]
      this.selectStudent.birthdayEndTime = this.time.birthdayTime[1]
      this.selectStudent.enrollmentStartTime = this.time.enrollmentTime[0]
      this.selectStudent.enrollmentEndime = this.time.enrollmentTime[1]
      this.selectStudent.graduationStartTime = this.time.graduationTime[0]
      this.selectStudent.graduationEndTime = this.time.graduationTime[1]
      this.pageListStudent()
    },
    // 重置按钮
    reset() {
      this.time = []
      this.selectStudent = {}
      this.pageListStudent()
    },
    insertHandler() {
      this.dialogMethod = 'post'
      this.dialogTitle = '新增学生'
      this.dialogVisible = true
      this.resetDialogForm()
    },
    updateRow(row) {
      this.dialogMethod = 'put'
      this.dialogTitle = '修改学生'
      this.dialogVisible = true
      this.dialogForm = JSON.parse(JSON.stringify(row))
    },
    // 删除
    deleteHandler() {
      deleteList(this.ids).then(res => {
        this.$message.success("删除成功")
        this.pageListStudent()
      })
    },
    deleteRow(row) {
      deleteList(row.id).then(res => {
        this.$message.success("删除成功")
        this.pageListStudent()
      })
    },
    // 重置弹框
    resetDialogForm() {
      this.dialogForm = this.$options.data().dialogForm
    },
    // 点击提交
    dialogSubmitHandler() {
      console.log(this.dialogForm.gender)
      editList(this.dialogMethod, this.dialogForm).finally(() => {
        this.dialogVisible = false
        this.pageListStudent()
      })
    },
    // 文件上传操作
    handleUploadSuccess(res, file, fileList, type) {
      if (res.code !== 200) this.$message.error((res.msg))
      else {
        if (type === 'AVATAR') {
          this.dialogForm.avatar = res.data
        } else {
          this.dialogForm.resume = res.data
        }
      }
    },
    handleBeforeUpload(file, type) {
      console.log(file)
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }
      let isImage
      let isDocument
      if (type === 'AVATAR') {
        isImage = file.type.startsWith('image')
        if (!isImage) {
          this.$message.error('上传图片格式!')
        }
      } else {
        isDocument = file.type.includes('doc') || file.type.includes('docx') || file.type.includes('pdf')
        if (!isDocument) {
          this.$message.error('上传文档格式!')
        }
      }
      return (isImage || isDocument) && isLt10M
    },
    handleRemove(file, fileList, type) {
      if (type === 'AVATAR') {
        this.dialogForm.avatar = ''
      } else {
        this.dialogForm.resume = ''
      }
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.pageListStudent()
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.pageListStudent()
      // console.log(`当前页: ${val}`);
    },
  }
}
</script>


<style scoped lang="scss">
$size: 150px;
$color: #DCDFE6;

.right-toolbar {
  float: right;
}


.avatar-uploader {
  width: $size;
  height: $size;
  border: 1px dashed $color;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 5px;
  font-size: 28px;
  color: rgba(96, 98, 102);

}

.img {
  margin-top: 10px;
  width: 100%;
  height: 100%;
  border-radius: 5px;
}
</style>
